package com.cmc.cloud.cmclink.doc.controller.admin.special;

import com.alibaba.excel.EasyExcel;
import com.cmc.cloud.cmclink.doc.constants.UrlConstants;
import com.cmc.cloud.cmclink.doc.convert.SuperWhitelistDgConvert;
import com.cmc.cloud.cmclink.doc.entity.SuperWhitelistDgDO;
import com.cmc.cloud.cmclink.doc.framework.listener.HsCodeExcelListener;
import com.cmc.cloud.cmclink.doc.service.SuperWhitelistDgService;
import com.cmc.cloud.cmclink.doc.vo.hscodevo.HsCodeImportVo;
import com.cmc.cloud.cmclink.doc.vo.superwhitelistvo.*;
import com.cmes.framework.biz.advice.annotations.UseResponsePropertyAdvice;
import com.cmes.framework.common.pojo.CommonResult;
import com.cmes.framework.common.pojo.PageResult;
import com.cmes.framework.excel.core.util.ExcelUtils;
import com.cmes.framework.operatelog.core.annotations.OperateLog;
import com.cmes.framework.operatelog.core.enums.OperateTypeEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * 有条件接载清单(DG)前端接口Controller
 *
 * @author codegen
 */
@Tag(name = "管理后台 - 有条件接载清单(DG)")
@RestController
@Validated
@RequestMapping(UrlConstants.APPLICATION_URL + "/superWhitelistDg")
public class SuperWhitelistDgController {

    @Resource
    private SuperWhitelistDgService superWhitelistDgService;

    @Operation(summary = "创建有条件接载清单(DG)")
    @PostMapping("/create")
    @PreAuthorize("@ss.hasPermission('doc:conditionallyDg:create')")
    @OperateLog(name = "创建有条件接载清单(DG)", type = OperateTypeEnum.CREATE)
    public CommonResult<Void> createSuperWhitelistDg(@Valid @RequestBody SuperWhitelistDgBaseVO createReqVO) {
        superWhitelistDgService.createSuperWhitelistDg(createReqVO);
        return CommonResult.success();
    }

    @Operation(summary = "更新有条件接载清单(DG)")
    @PostMapping("/update")
    @PreAuthorize("@ss.hasPermission('doc:conditionallyDg:edit')")
    @OperateLog(name = "更新有条件接载清单(DG)", type = OperateTypeEnum.UPDATE)
    public CommonResult<Void> updateSuperWhitelistDg(@Valid @RequestBody SuperWhitelistDgUpdateReqVO updateReqVO) {
        superWhitelistDgService.updateSuperWhitelistDg(updateReqVO);
        return CommonResult.success();
    }

    @Operation(summary = "删除有条件接载清单(DG)")
    @PostMapping("/delete/{id}")
    @PreAuthorize("@ss.hasPermission('doc:conditionallyDg:delete')")
    @Parameter(name = "id", description = "编号", required = true)
    @OperateLog(name = "删除有条件接载清单(DG)", type = OperateTypeEnum.DELETE)
    public CommonResult<Void> deleteSuperWhitelistDg(@PathVariable("id") Long id) {
        superWhitelistDgService.deleteSuperWhitelistDg(id);
        return CommonResult.success();
    }

    @Operation(summary = "获得有条件接载清单(DG)")
    @GetMapping("/get/{id}")
    @PreAuthorize("@ss.hasPermission('doc:conditionallyDg:preview')")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @OperateLog(name = "获得有条件接载清单(DG)", type = OperateTypeEnum.GET)
    public CommonResult<SuperWhitelistDgRespVO> getSuperWhitelistDg(@PathVariable("id") Long id) {
        SuperWhitelistDgDO superWhitelistDg = superWhitelistDgService.getSuperWhitelistDg(id);
        return CommonResult.success(SuperWhitelistDgConvert.INSTANCE.convert(superWhitelistDg));
    }

    @Operation(summary = "获得有条件接载清单(DG)列表")
    @GetMapping("/list")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @OperateLog(name = "获得有条件接载清单(DG)", type = OperateTypeEnum.GET)
    public CommonResult<List<SuperWhitelistDgRespVO>> getSuperWhitelistDgList(@RequestParam("ids") Collection<Long> ids) {
        List<SuperWhitelistDgDO> list = superWhitelistDgService.getSuperWhitelistDgList(ids);
        return CommonResult.success(SuperWhitelistDgConvert.INSTANCE.convertList(list));
    }

    @Operation(summary = "获得有条件接载清单(DG)分页")
    @PostMapping("/page")
    @PreAuthorize("@ss.hasPermission('doc:conditionallyDg:search')")
    @OperateLog(name = "获得有条件接载清单(DG)", type = OperateTypeEnum.GET)
    @UseResponsePropertyAdvice
    public CommonResult<PageResult<SuperWhitelistDgRespVO>> getSuperWhitelistDgPage(@RequestBody @Valid SuperWhitelistDgPageReqVO pageVO) {
        PageResult<SuperWhitelistDgDO> pageResult = superWhitelistDgService.getSuperWhitelistDgPage(pageVO);
        List<SuperWhitelistDgRespVO> results = SuperWhitelistDgConvert.INSTANCE.convertList(pageResult.getList());
        return CommonResult.success(new PageResult<>(results, pageResult.getTotal()));
    }

    @GetMapping("/export")
    @PreAuthorize("@ss.hasPermission('doc:conditionallyDg:export')")
    @Operation(summary = "excel导出")
    @OperateLog(name = "excel导出(DG)", type = OperateTypeEnum.EXPORT)
    @Parameter(name = "specialCargoType", description = "特种货类型")
    @Parameter(name = "praNo", description = "超级白名单号")
    @Parameter(name = "pors", description = "接货地(多个)")
    @Parameter(name = "pols", description = "装货港(多个)")
    @Parameter(name = "pods", description = "卸货港(多个)")
    @Parameter(name = "dels", description = "目的地(多个)")
    public void exportExcelTemplate(HttpServletResponse response, @RequestParam(value = "specialCargoType") String specialCargoType
            , @RequestParam(value = "praNo") String praNo
            , @RequestParam(value = "pors") String pors
            , @RequestParam(value = "pols") String pols
            , @RequestParam(value = "pods") String pods
            , @RequestParam(value = "dels") String dels) throws IOException {
        SuperWhitelistReqVO reqVO = SuperWhitelistReqVO.builder().specialCargoType(specialCargoType).praNo(praNo).pors(pors).pols(pols).pods(pods).dels(dels).build();
        List<SuperWhitelistDgDO> exportList = superWhitelistDgService.getExportList(reqVO);
        List<SuperWhitelistDgExportVO> superWhitelistDgExportVOList = SuperWhitelistDgConvert.INSTANCE.concertExportList(exportList);
        // FIXME 一定要向response写数据之前设置响应头，否则会出现文件下载失败
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("SuperWhitelistDg.xlsx", StandardCharsets.UTF_8.name()));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        ExcelUtils.write(response, "SuperWhitelistDg.xls", "模版", SuperWhitelistDgExportVO.class, superWhitelistDgExportVOList);
    }

    @Operation(summary = "从源数据复制信息")
    @PostMapping("/copyFromHistory")
    @PreAuthorize("@ss.hasPermission('doc:conditionallyDg:copyAdd')")
    @OperateLog(name = "从源数据复制信息(DG)", type = OperateTypeEnum.GET)
    public CommonResult<Void> copyFromHistory(@Valid @RequestBody SpecialWhiteListCopyReqVO originalVo) {
        superWhitelistDgService.copyFromHistory(originalVo);
        return CommonResult.success();
    }

    @PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "excel新增导入")
    @PreAuthorize("@ss.hasPermission('doc:conditionallyDg:upload')")
    @OperateLog(name = "excel新增导入(DG)", type = OperateTypeEnum.IMPORT)
    public CommonResult<Integer> excelCreateImport(@RequestPart @RequestParam(value = "file") MultipartFile file) throws IOException {
        HsCodeExcelListener hsCodeExcelListener = new HsCodeExcelListener(new ArrayList<>());
        List<SuperWhitelistDgBaseVO> importVos = EasyExcel.read(file.getInputStream(), HsCodeImportVo.class, hsCodeExcelListener).autoCloseStream(true).doReadAllSync();
        Integer num = superWhitelistDgService.saveImportData(importVos);
        return CommonResult.success(num);
    }

    @GetMapping("/deleteFile/{id}")
    @Operation(summary = "文件删除")
    @PreAuthorize("@ss.hasPermission('doc:conditionallyDg:deleteUpload')")
    @OperateLog(name = "文件删除", type = OperateTypeEnum.DELETE)
    public CommonResult deleteFile(@PathVariable("id") Long id) {
        superWhitelistDgService.deleteFile(id);
        return CommonResult.success();
    }
}
